package com.project.market.controller;

import com.project.market.db.domain.MarketAdmin;
import com.project.market.service.AdminAuthService;
import com.project.market.service.impl.AdminAuthServiceImpl;
import com.project.market.util.JacksonUtil;
import com.project.market.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/admin/auth/*")
public class AdminAuthController extends HttpServlet {

    private AdminAuthService adminAuthService = new AdminAuthServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/auth/", "");
        if ("login".equals(op)) {
            login(req, resp);
        } else if("logout".equals(op)){
            logout(req,resp);
        }
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        session.invalidate();
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok()));
        resp.setHeader("refresh","0;url = "+req.getContextPath()+"/login");

    }

    /*
    登录的业务逻辑
    1.接收用户传递过来的请求参数信息
    2。处理具体的业务逻辑：拿用户名、密码到数据库中进行比对
    3。返回结果
    存在跨域问题
     */
    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        BufferedReader reader = req.getReader();
        String s = reader.readLine();
        System.out.println(s);

        // 工具类，从JSON字符串中取出字段属性对应的值
        String username = JacksonUtil.parseString(s, "username");
        String password = JacksonUtil.parseString(s, "password");

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            Object fail = ResponseUtil.fail(605, "用户账户或密码不允许为空");
            resp.getWriter().println(fail);
            return;
        }

        // 后续该接口要求返回一个avatar头像，这个属性再数据库里面
        MarketAdmin admin = adminAuthService.login(username, password);
        // 根据admin是否为null，判断是否登录成功
        if (admin == null) {
            // 登陆失败
            // {"errno":605,"errmsg":"用户帐号或密码不正确"}
            Object fail = ResponseUtil.fail(605, "用户账户或密码不正确");
            // 把map对象转换从JSON字符串
            String responseBody = JacksonUtil.writeValueAsString(fail);
            resp.getWriter().println(responseBody);
            return;
        }
        // 登录成功
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> adminInfo = new HashMap<>();
        adminInfo.put("nickName", admin.getUsername());
        adminInfo.put("avatar", admin.getAvatar());
        HttpSession session = req.getSession();
        String id = session.getId();
        session.setAttribute("admin", admin);
        result.put("adminInfo", adminInfo);
        result.put("token", id);

        Object ok = ResponseUtil.ok(result);
        String responseBody = JacksonUtil.writeValueAsString(ok);
        resp.getWriter().println(responseBody);
        return;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/auth/", "");
        if ("info".equals(op)) {
            info(req, resp);
        }
    }

    // 个人信息接口，要求返回管理员个人信息：用户名、头像
    private void info(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //在当前servlet中，从session域中再次获取admin信息
        HttpSession session = req.getSession();
        //获取登录时，放入session域里面的数据
        MarketAdmin admin = (MarketAdmin) session.getAttribute("admin");
        //roles 角色（涉及到权限，项目一不用去写） perms 权限 项目一不用去写
        Map<String, Object> result = new HashMap<>();
        result.put("roles", new String[]{"超级管理员"});
        result.put("name", admin.getUsername());
        result.put("perms", new String[]{"*"});
        result.put("avatar", admin.getAvatar());
        Object ok = ResponseUtil.ok(result);
        String s = JacksonUtil.writeValueAsString(ok);
        resp.getWriter().println(s);
    }
}
